<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消费税率" prop="consumptionRate">
        <el-input
          v-model="queryParams.consumptionRate"
          placeholder="请输入消费税率"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="增值税率" prop="valueAddedRate">
        <el-input
          v-model="queryParams.valueAddedRate"
          placeholder="请输入增值税率"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:categories:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoriesList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类名称" prop="name" />
      <!-- <el-table-column label="父分类" align="center" prop="parentId" /> -->
      <el-table-column label="消费税率" align="center" prop="consumptionRate" width="200" />
      <!-- <el-table-column label="消费税计算公式" align="center" prop="consumptionCumpte" /> -->
      <!-- <el-table-column label="消费税计算公式" align="center" prop="consumptionDataType" /> -->
      <el-table-column label="增值税率" align="center" prop="valueAddedRate">
        <template #default="scope">
          <span>{{ formatValueAddedRate(scope.row.valueAddedRate) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="增值税计算公式" align="center" prop="valueAddedCumpte" /> -->
      <!-- <el-table-column label="增值税计算公式" align="center" prop="valueAddedDatatype" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:categories:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['manage:categories:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:categories:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改增值税分类对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="categoriesRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="categoriesOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择父分类"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="消费税率" prop="consumptionRate">
          <el-input v-model="form.consumptionRate" placeholder="请输入消费税率" />
        </el-form-item>
        <!-- <el-form-item label="消费税计算公式" prop="consumptionCumpte">
          <el-input v-model="form.consumptionCumpte" placeholder="请输入消费税计算公式" />
        </el-form-item> -->
        <!-- <el-form-item label="消费税计算公式" prop="consumptionDataType">
          <el-input v-model="form.consumptionDataType" placeholder="请输入消费税计算公式" />
        </el-form-item> -->
        <el-form-item label="增值税一般纳税人税率" prop="valueAddedRateGeneral">
          <el-input v-model="form.valueAddedRateGeneral" placeholder="请输入一般纳税人税率，如 13%" />
        </el-form-item>
        <el-form-item label="增值税小规模纳税人税率" prop="valueAddedRateSmall">
          <el-input v-model="form.valueAddedRateSmall" placeholder="请输入小规模纳税人税率，如 3%" />
        </el-form-item>
        <!-- 原有增值税率输入框注释掉 -->
        <!-- <el-form-item label="增值税率" prop="valueAddedRate">
          <el-input v-model="form.valueAddedRate" placeholder="请输入增值税率" />
        </el-form-item> -->
        <!-- <el-form-item label="增值税计算公式" prop="valueAddedCumpte">
          <el-input v-model="form.valueAddedCumpte" placeholder="请输入增值税计算公式" />
        </el-form-item> -->
        <!-- <el-form-item label="增值税计算公式" prop="valueAddedDatatype">
          <el-input v-model="form.valueAddedDatatype" placeholder="请输入增值税计算公式" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Categories">
import { listCategories, getCategories, delCategories, addCategories, updateCategories } from "@/api/manage/categories";

const { proxy } = getCurrentInstance();

const categoriesList = ref([]);
const categoriesOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    name: null,
    parentId: null,
    consumptionRate: null,
    consumptionCumpte: null,
    consumptionDataType: null,
    valueAddedRate: null,
    valueAddedCumpte: null,
    valueAddedDatatype: null
  },
  rules: {
    name: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    parentId: [
      { required: true, message: "父分类，0表示顶级分类不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const formatValueAddedRate = (rateStr) => {
  if (!rateStr) return '';
  try {
    // 尝试解析伪JSON
    const obj = {};
    rateStr.replace(/[{}'\s]/g, '').split(',').forEach(pair => {
      const [k, v] = pair.split(':');
      if (k && v) obj[k] = v;
    });
    let arr = [];
    if (obj['一般纳税人']) arr.push(`一般纳税人: ${obj['一般纳税人']}`);
    if (obj['小规模纳税人']) arr.push(`小规模纳税人: ${obj['小规模纳税人']}`);
    return arr.join('，');
  } catch {
    return rateStr;
  }
};

/** 查询增值税分类列表 */
function getList() {
  loading.value = true;
  listCategories(queryParams.value).then(response => {
    categoriesList.value = proxy.handleTree(response.data, "id", "parentId");
    loading.value = false;
  });
}

/** 查询增值税分类下拉树结构 */
function getTreeselect() {
  listCategories().then(response => {
    categoriesOptions.value = [];
    const data = { id: 0, name: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    categoriesOptions.value.push(data);
  });
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    parentId: null,
    consumptionRate: null,
    consumptionCumpte: null,
    consumptionDataType: null,
    valueAddedRate: null,
    valueAddedCumpte: null,
    valueAddedDatatype: null,
    valueAddedRateGeneral: null,
    valueAddedRateSmall: null
  };
  proxy.resetForm("categoriesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加增值税分类";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getCategories(row.id).then(response => {
    form.value = response.data;
    // 解析伪JSON到两个输入框
    if (form.value.valueAddedRate) {
      try {
        const obj = {};
        form.value.valueAddedRate.replace(/[{}'\s]/g, '').split(',').forEach(pair => {
          const [k, v] = pair.split(':');
          if (k && v) obj[k] = v;
        });
        form.value.valueAddedRateGeneral = obj['一般纳税人'] || '';
        form.value.valueAddedRateSmall = obj['小规模纳税人'] || '';
      } catch {}
    }
    open.value = true;
    title.value = "修改增值税分类";
  });
}

/** 提交按钮 */
function submitForm() {
  // 合成 valueAddedRate 字段
  form.value.valueAddedRate = `{一般纳税人:'${form.value.valueAddedRateGeneral || ''}', 小规模纳税人:'${form.value.valueAddedRateSmall || ''}'}`;
  proxy.$refs["categoriesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCategories(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategories(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除增值税分类编号为"' + row.name + '"的数据项？').then(function() {
    return delCategories(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>
